<template>
  <div class="menu-container">
    <div class="filter-container">
      <button-box class="filter-item" type="primary" icon="el-icon-plus" text="添加菜单" @click="handleCreate"></button-box>
      <button-box class="filter-item" type="success" text="刷新数据" @click="handleRefresh"></button-box>
      <button-box class="filter-item" type="info" icon="el-icon-download" text="导出Excel" @click="exportExcelData"></button-box>
      
      <!-- 使用el-dropdown包裹ButtonBox -->
      <el-dropdown class="filter-item" trigger="click" @command="handleImportCommand">
        <button-box type="warning" icon="el-icon-upload2" text="导入数据"></button-box>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="importExcel">导入Excel</el-dropdown-item>
            <el-dropdown-item command="downloadTemplate">下载模板</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      
      <input 
        type="file" 
        ref="excelFileInput" 
        style="display: none" 
        accept=".xlsx,.xls" 
        @change="importExcelData"
      />
    </div>

    <el-table
      v-loading="listLoading"
      :data="tableData"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="菜单名称" min-width="180"></el-table-column>
      <el-table-column prop="path" label="路径" min-width="180"></el-table-column>
      <el-table-column prop="component" label="组件路径" min-width="200"></el-table-column>
      <el-table-column prop="perms" label="权限标识" min-width="150"></el-table-column>
      <el-table-column prop="icon" label="图标" min-width="100">
        <template #default="scope">
          <i :class="scope.row.icon"></i>
          <span style="margin-left: 5px;">{{ scope.row.icon }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" min-width="80">
        <template #default="scope">
          <el-tag :type="scope.row.type === 'M' ? 'primary' : (scope.row.type === 'C' ? 'success' : 'warning')">
            {{ scope.row.type === 'M' ? '菜单' : (scope.row.type === 'C' ? '目录' : '按钮') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" min-width="80"></el-table-column>
      <el-table-column prop="status" label="状态" min-width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <div class="operation-buttons">
            <button-box
              size="mini"
              type="primary"
              icon="el-icon-edit"
              text="编辑"
              @click="handleEdit(scope.row)"
            ></button-box>
            
            <!-- 使用el-dropdown包裹ButtonBox -->
            <el-dropdown v-if="scope.row.type !== 'F'" trigger="click" @command="command => handleCommand(command, scope.row)">
              <button-box
                type="success"
                size="mini"
                icon="el-icon-plus"
                text="添加"
              ></button-box>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="scope.row.type !== 'F'" command="addChild">添加子菜单</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.type === 'M'" command="addButton">添加按钮</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <button-box
              size="mini"
              type="danger"
              icon="el-icon-delete"
              text="删除"
              confirm="确认删除该菜单及其子菜单?"
              @click="handleDelete(scope.row)"
            ></button-box>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或更新菜单对话框 -->
    <dialog-box
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @confirm="submitForm"
      @cancel="closeDialog"
    >
      <el-form :model="menuForm" :rules="rules" ref="menuForm" label-width="100px">
        <el-form-item label="上级菜单">
          <el-cascader
            v-model="menuForm.parentId"
            :options="menuOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            clearable
            placeholder="顶级菜单"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio label="M">菜单</el-radio>
            <el-radio label="C">目录</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="path" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.path"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 'M'">
          <el-input v-model="menuForm.component" placeholder="如：layout/index"></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="perms">
          <el-input v-model="menuForm.perms" placeholder="如：system:user:list"></el-input>
          <span class="form-help">权限标识格式为：模块:操作:资源</span>
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.icon" placeholder="如：el-icon-user">
            <template #prepend>
              <i :class="menuForm.icon"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="menuForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </dialog-box>

    <!-- Excel导入说明对话框 -->
    <dialog-box
      title="Excel导入说明"
      :visible.sync="excelHelpVisible"
      width="500px"
      @cancel="closeExcelHelp"
    >
      <div class="excel-help">
        <h3>导入说明：</h3>
        <ul>
          <li v-for="(item, index) in excelImportInstructions" :key="index">{{ item }}</li>
        </ul>
        <div class="excel-help-actions">
          <button-box type="primary" text="下载Excel模板" @click="downloadExcelTemplate"></button-box>
          <button-box type="success" text="选择Excel文件导入" @click="triggerExcelImport"></button-box>
        </div>
      </div>
    </dialog-box>
  </div>
</template>

<script>
// 不再需要导入API
// import { getMenuListApi, getMenuTreeApi, createMenuApi, updateMenuApi, deleteMenuApi, getMenuDetailApi } from '@/api'

// 导入Excel工具
import { exportTableToExcel, importExcel } from '@/utils/excel'
import { treeToFlat, flatToTree, getMenuExcelHeader } from '@/utils/menuTransformer'
import { generateMenuExcelTemplate, getExcelImportInstructions } from '@/utils/excelTemplate'

// 本地存储的键名
const MENU_DATA_KEY = 'vue_admin_menu_data'

export default {
  name: 'MenuManagement',
  data() {
    return {
      tableData: [],
      listLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      menuForm: {
        id: undefined,
        parentId: null,
        name: '',
        path: '',
        component: '',
        perms: '',
        icon: '',
        type: 'M',
        sort: 0,
        status: '1'
      },
      rules: {
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
        path: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }],
        perms: [{ pattern: /^[a-z]+:[a-z]+:[a-z]+$/, message: '权限标识格式不正确', trigger: 'blur' }]
      },
      menuOptions: [],
      excelHelpVisible: false,
      excelImportInstructions: [],
      pageSizes: [10, 20, 50, 100],
      paginationLayout: "total, sizes, prev, pager, next, jumper",
      paginationTimer: null
    }
  },
  created() {
    // 初始化加载菜单数据
    this.fetchData()
    // 加载Excel导入说明
    this.excelImportInstructions = getExcelImportInstructions()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      
      // 从localStorage加载数据
      setTimeout(() => {
        this.loadLocalData()
        this.listLoading = false
        this.generateMenuOptions()
      }, 300)
    },
    
    // 添加刷新方法
    handleRefresh() {
      // 关闭所有对话框
      this.dialogVisible = false
      this.excelHelpVisible = false
      
      // 刷新数据
      this.fetchData()
    },
    
    // 从localStorage加载数据
    loadLocalData() {
      try {
        const savedData = localStorage.getItem(MENU_DATA_KEY)
        if (savedData) {
          this.tableData = JSON.parse(savedData)
        } else {
          // 如果没有保存的数据，使用默认数据
          this.loadDefaultData()
          // 保存默认数据到localStorage
          this.saveToLocalStorage()
        }
      } catch (error) {
        console.error('从localStorage加载数据失败:', error)
        this.loadDefaultData()
      }
    },
    
    // 保存数据到localStorage
    saveToLocalStorage() {
      try {
        localStorage.setItem(MENU_DATA_KEY, JSON.stringify(this.tableData))
      } catch (error) {
        console.error('保存数据到localStorage失败:', error)
        this.$messageBox.error('保存数据失败，请检查浏览器存储空间')
      }
    },
    
    // 加载默认数据
    loadDefaultData() {
      this.tableData = [
        {
          id: 1,
          name: '系统管理',
          path: '/system',
          component: 'Layout',
          perms: 'system',
          icon: 'el-icon-setting',
          type: 'C',
          sort: 1,
          status: '1',
          children: [
            {
              id: 11,
              name: '用户管理',
              path: '/system/user',
              component: 'system/user/index',
              perms: 'system:user',
              icon: 'el-icon-user',
              type: 'M',
              sort: 1,
              status: '1',
              children: [
                {
                  id: 111,
                  name: '用户查询',
                  perms: 'system:user:query',
                  type: 'F',
                  sort: 1,
                  status: '1'
                },
                {
                  id: 112,
                  name: '用户新增',
                  perms: 'system:user:add',
                  type: 'F',
                  sort: 2,
                  status: '1'
                },
                {
                  id: 113,
                  name: '用户修改',
                  perms: 'system:user:edit',
                  type: 'F',
                  sort: 3,
                  status: '1'
                },
                {
                  id: 114,
                  name: '用户删除',
                  perms: 'system:user:remove',
                  type: 'F',
                  sort: 4,
                  status: '1'
                },
                {
                  id: 115,
                  name: '重置密码',
                  perms: 'system:user:resetPwd',
                  type: 'F',
                  sort: 5,
                  status: '1'
                }
              ]
            },
            {
              id: 12,
              name: '角色管理',
              path: '/system/role',
              component: 'system/role/index',
              perms: 'system:role',
              icon: 'el-icon-user-solid',
              type: 'M',
              sort: 2,
              status: '1'
            },
            {
              id: 13,
              name: '菜单管理',
              path: '/system/menu',
              component: 'system/menu/index',
              perms: 'system:menu',
              icon: 'el-icon-menu',
              type: 'M',
              sort: 3,
              status: '1'
            }
          ]
        }
      ]
    },
    
    generateMenuOptions() {
      // 生成级联选择器的选项
      this.menuOptions = this.formatOptions(this.tableData)
    },
    
    formatOptions(data) {
      // 将菜单数据格式化为级联选择器可用的格式，只允许选择目录和菜单
      let options = []
      if (data && data.length > 0) {
        options = data.filter(item => item.type !== 'F').map(item => {
          const option = {
            id: item.id,
            name: item.name,
            type: item.type
          }
          if (item.children && item.children.length > 0) {
            const children = this.formatOptions(item.children)
            if (children.length > 0) {
              option.children = children
            }
          }
          return option
        })
      }
      return options
    },
    
    resetForm() {
      this.menuForm = {
        id: undefined,
        parentId: null,
        name: '',
        path: '',
        component: '',
        perms: '',
        icon: '',
        type: 'M',
        sort: 0,
        status: '1'
      }
    },
    
    handleCreate() {
      this.resetForm()
      this.dialogTitle = '添加菜单'
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.menuForm) {
          this.$refs.menuForm.clearValidate()
        }
      })
    },
    
    handleEdit(row) {
      // 直接使用传入的行数据
      this.menuForm = JSON.parse(JSON.stringify(row))
      if (this.menuForm.parentId === 0) {
        this.menuForm.parentId = null
      }
      
      this.dialogTitle = '编辑菜单'
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.menuForm) {
          this.$refs.menuForm.clearValidate()
        }
      })
    },
    
    handleAddChild(row) {
      this.resetForm()
      this.menuForm.parentId = row.id
      this.menuForm.type = row.type === 'C' ? 'M' : 'F'
      this.dialogTitle = row.type === 'C' ? '添加菜单' : '添加子菜单'
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.menuForm) {
          this.$refs.menuForm.clearValidate()
        }
      })
    },
    
    handleAddButton(row) {
      this.resetForm()
      this.menuForm.parentId = row.id
      this.menuForm.type = 'F'
      this.menuForm.perms = row.perms + ':'
      this.dialogTitle = '添加按钮权限'
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.menuForm) {
          this.$refs.menuForm.clearValidate()
        }
      })
    },
    
    handleDelete(row) {
      // 使用ButtonBox的confirm属性代替这里的确认对话框
      // 从本地数据中删除
      this.deleteTreeNode(this.tableData, row.id)
      this.$messageBox.success('删除成功')
      this.generateMenuOptions()
      // 保存更改到localStorage
      this.saveToLocalStorage()
    },
    
    submitForm() {
      this.$refs.menuForm.validate(valid => {
        if (valid) {
          const isEdit = this.menuForm.id !== undefined
          
          // 直接操作本地数据
          if (isEdit) {
            // 编辑现有菜单
            this.updateTreeNode(this.tableData, this.menuForm)
          } else {
            // 添加新菜单
            if (!this.menuForm.parentId) {
              // 添加顶级菜单
              const newId = Math.max(...this.getIds(this.tableData)) + 1
              const newMenu = {...this.menuForm, id: newId}
              if (newMenu.type !== 'F') newMenu.children = []
              this.tableData.push(newMenu)
            } else {
              // 添加子菜单
              this.addChildNode(this.tableData, this.menuForm)
            }
          }
          
          // 通过方法关闭对话框
          this.closeDialog()
          this.$messageBox.success(isEdit ? '编辑成功' : '创建成功')
          this.generateMenuOptions()
          
          // 保存更改到localStorage
          this.saveToLocalStorage()
        }
      })
    },
    
    // 从树形数据中删除节点
    deleteTreeNode(data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          data.splice(i, 1)
          return true
        }
        if (data[i].children && data[i].children.length > 0) {
          if (this.deleteTreeNode(data[i].children, id)) {
            return true
          }
        }
      }
      return false
    },
    
    getIds(data) {
      let ids = data.map(item => item.id)
      data.forEach(item => {
        if (item.children && item.children.length > 0) {
          ids = [...ids, ...this.getIds(item.children)]
        }
      })
      return ids
    },
    
    updateTreeNode(data, updatedNode) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === updatedNode.id) {
          // 保留children字段
          const children = data[i].children
          data[i] = {...updatedNode}
          if (children) {
            data[i].children = children
          }
          return true
        }
        if (data[i].children && data[i].children.length > 0) {
          if (this.updateTreeNode(data[i].children, updatedNode)) {
            return true
          }
        }
      }
      return false
    },
    
    addChildNode(data, newNode) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === newNode.parentId) {
          const newId = Math.max(...this.getIds(this.tableData)) + 1
          const childNode = {...newNode, id: newId}
          if (childNode.type !== 'F') childNode.children = []
          if (!data[i].children) data[i].children = []
          data[i].children.push(childNode)
          return true
        }
        if (data[i].children && data[i].children.length > 0) {
          if (this.addChildNode(data[i].children, newNode)) {
            return true
          }
        }
      }
      return false
    },

    // 处理下拉菜单命令
    handleCommand(command, row) {
      if (command === 'addChild') {
        this.handleAddChild(row)
      } else if (command === 'addButton') {
        this.handleAddButton(row)
      }
    },
    
    // 处理添加选项
    // 关闭菜单对话框
    closeDialog() {
      // 正确设置dialogVisible为false
      this.dialogVisible = false
    },
    
    // 关闭Excel帮助对话框
    closeExcelHelp() {
      // 正确设置excelHelpVisible为false
      this.excelHelpVisible = false
    },
    
    handleAddOptions(row) {
      if (row.type === 'M') {
        // 如果是菜单，显示下拉选项
        this.$confirm('请选择要添加的类型', '添加', {
          confirmButtonText: '添加子菜单',
          cancelButtonText: '添加按钮',
          distinguishCancelAndClose: true,
          type: 'info'
        }).then(() => {
          this.handleAddChild(row)
        }).catch(action => {
          if (action === 'cancel') {
            this.handleAddButton(row)
          }
        })
      } else if (row.type !== 'F') {
        // 如果不是按钮，直接添加子菜单
        this.handleAddChild(row)
      }
    },
    
    // 处理导入命令
    handleImportCommand(command) {
      if (command === 'importExcel') {
        // 直接触发文件选择
        this.triggerExcelImport()
      } else if (command === 'downloadTemplate') {
        this.downloadExcelTemplate()
      }
    },
    
    // 导出菜单数据为Excel
    exportExcelData() {
      // 准备导出数据
      const exportData = this.tableData.map(item => {
        // 处理层级显示
        const newItem = { ...item }
        // 添加其他需要处理的字段
        return newItem
      })
      
      // 定义表头
      const columns = [
        { label: 'ID', prop: 'id' },
        { label: '菜单名称', prop: 'title' },
        { label: '路径', prop: 'path' },
        { label: '组件', prop: 'component' },
        { label: '权限标识', prop: 'permission' },
        { label: '图标', prop: 'icon' },
        { label: '排序', prop: 'sort' }
      ]
      
      // 导出Excel
      exportTableToExcel(exportData, columns, '菜单数据')
    },
    
    // 下载Excel模板
    downloadExcelTemplate() {
      const success = generateMenuExcelTemplate()
      if (success) {
        this.$messageBox.success('Excel模板下载成功')
      } else {
        this.$messageBox.error('Excel模板下载失败')
      }
    },
    
    // 从Excel导入菜单数据
    importExcelData(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 显示加载状态
      this.listLoading = true
      
      importExcel(file, (data, error) => {
        this.listLoading = false
        
        if (error || !data) {
          console.error('导入Excel失败:', error)
          this.$messageBox.error('导入失败，请检查文件格式')
          return
        }
        
        try {
          // 验证数据格式
          if (!Array.isArray(data) || data.length === 0) {
            this.$messageBox.error('导入数据为空，请检查文件内容')
            return
          }
          
          console.log('导入的Excel数据:', data)
          
          // 将扁平数据转换为树形结构
          const treeData = flatToTree(data)
          
          console.log('转换后的树形数据:', treeData)
          
          // 检查转换后的数据是否为空
          if (!treeData || treeData.length === 0) {
            this.$messageBox.error('数据转换失败，请确保Excel格式正确')
            return
          }
          
          // 更新数据
          this.tableData = treeData
          this.generateMenuOptions()
          this.saveToLocalStorage()
          
          this.$messageBox.success('菜单数据导入成功')
        } catch (error) {
          console.error('处理导入数据失败:', error)
          this.$messageBox.error(`导入失败: ${error.message || '数据格式不正确'}`)
        }
      })
      
      // 重置input，允许再次选择同一个文件
      event.target.value = ''
    },
    
    // 导出菜单数据为JSON
    exportMenuData() {
      try {
        // 将树形结构转换为扁平结构以便导出
        const flatData = treeToFlat(this.tableData)
        // 导出Excel
        exportTableToExcel(flatData, getMenuExcelHeader(), '菜单数据')
        this.$messageBox.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$messageBox.error('导出失败: ' + error.message)
      }
    },
    
    // 触发Excel文件选择
    triggerExcelImport() {
      this.$refs.excelFileInput.click()
    },

    // 显示Excel导入说明对话框
    showExcelHelp() {
      this.excelHelpVisible = true
    },

    handlePaginationChange() {
      if (this.paginationTimer) clearTimeout(this.paginationTimer)
      this.paginationTimer = setTimeout(() => this.getList(), 300)
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  
  .filter-container {
    margin-bottom: 15px;
    padding: 8px 0;
    
    .filter-item {
      margin-right: 10px;
      height: 32px;
      line-height: 1;
      padding: 7px 15px;
    }
  }
  
  .form-help {
    color: #909399;
    font-size: 12px;
    margin-top: 3px;
    display: inline-block;
  }
  
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 5px; /* 按钮之间的间距 */
    justify-content: center;
    
    .el-button, .el-dropdown {
      margin: 0; /* 覆盖element-ui默认的按钮margin */
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  .excel-help {
    h3 {
      margin-top: 0;
      margin-bottom: 15px;
      color: #303133;
    }
    
    ul {
      padding-left: 20px;
      margin-bottom: 20px;
      
      li {
        line-height: 1.8;
        color: #606266;
      }
    }
    
    .excel-help-actions {
      text-align: center;
      margin-top: 20px;
    }
  }
  
  @media (max-width: 768px) {
    padding: 0;
    
    .filter-container {
      margin-bottom: 12px;
      padding: 6px 0;
    }
    
    .el-dialog {
      width: 95% !important;
    }
  }
}
</style> 